﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace Coding4Fun.WheresMyCar
{
	public class ImageConverter : IValueConverter
	{
        public static Dictionary<string, WeakReference> Cache { get; private set; }

        static ImageConverter()
        {
            Cache = new Dictionary<string, WeakReference>();
        }

		#region IValueConverter Members

		public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
            if (value != null && !string.IsNullOrEmpty(value.ToString()))
            {
                string fn = value.ToString();

                if (Cache.ContainsKey(fn))
                    if (Cache[fn].IsAlive)
                        return Cache[fn].Target;
                    else
                        Cache.Remove(fn);

                try
                {
                    BitmapImage bs = null;
                    using (var myStore = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (myStore.FileExists(fn))
                        {
                            using (var photoStream = myStore.OpenFile(fn, FileMode.Open))
                            {
                                bs = new BitmapImage();
                                bs.SetSource(photoStream);
                            }
                        }
                        else
                            bs = (new BitmapImage(new Uri(fn, UriKind.Relative)));

                        if( parameter == null || parameter.ToString() != "no-cache")
                            Cache.Add(fn, new WeakReference(bs));
                        return bs;
                    }
                }
                catch
                {
                    // Errors will be handled silently
                }
            }

		    // If all else fails...
			return null;
		}

		public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			throw new NotImplementedException();
		}

		#endregion
	}
}
